package com.cabal.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cabal.auth.dao.CabalAuthMapper;
import com.cabal.auth.dao.CabalCharacterGmBuffMapper;
import com.cabal.auth.dto.*;
import com.cabal.auth.entity.CabalCharacter;
import com.cabal.auth.entity.CabalCharacterGmBuff;
import com.cabal.auth.entity.CabalSkillData;
import com.cabal.auth.entity.CabalTitleData;
import com.cabal.auth.vo.CabalAuthVo;
import com.cabal.common.constants.SystemConstants;
import com.cabal.common.errcode.ErrorCodeEnum;
import com.cabal.common.util.DateApiUtil;
import com.cabal.common.util.HighLowSwapUtil;
import com.cabal.common.util.SnowflakeIdUtil;
import com.cabal.common.util.TmsServiceException;
import com.cabal.config.DynamicDataSourceContextHolder;
import com.cabal.contribute.dao.CabalContributePointAccountMapper;
import com.cabal.contribute.entity.CabalContributePointAccount;
import com.cabal.contribute.entity.CabalContributePointLog;
import com.cabal.contribute.service.CabalContributePointService;
import com.cabal.mall.dao.*;
import com.cabal.mall.entity.*;
import com.cabal.mall.service.CabalMallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;

@Slf4j
@Service
public class CabalMallServiceImpl implements CabalMallService {

    @Resource
    private CabalMallSellItemMapper cabalMallSellItemMapper;

    @Resource
    private CabalMallBuyRecordMapper cabalMallBuyRecordMapper;

    @Resource
    private CabalMallCoinAccountMapper cabalMallCoinAccountMapper;

    @Resource
    private CabalMallCoinLogMapper cabalMallCoinLogMapper;

    @Resource
    private CabalAuthMapper cabalAuthMapper;

    @Resource
    private CabalContributePointAccountMapper cabalContributePointAccountMapper;

    @Resource
    private CabalContributePointService cabalContributePointService;

    @Resource
    private CabalCharacterGmBuffMapper cabalCharacterGmBuffMapper;

    @Resource
    private CabalCharacterInfoMapper cabalCharacterInfoMapper;

    @Value("${GM_BUFF_HEX:3B01015E00}")
    private String gmBuffHex;

    @Resource
    private CabalAvatarItemMapper cabalAvatarItemMapper;

    @Resource
    private CabalDungeonWarpIdConfigMapper cabalDungeonWarpIdConfigMapper;

    @Resource
    private CabalEquipmentSellConfigMapper cabalEquipmentSellConfigMapper;

    @Resource
    private CabalEmsEventNpcItemPriceMapper cabalEmsEventNpcItemPriceMapper;

    @Resource
    private CabalPrizeDrawAccountMapper cabalPrizeDrawAccountMapper;

    @Resource
    private CabalLotteryPoolConfigMapper cabalLotteryPoolConfigMapper;

    @Resource
    private CabalPrizeDrawLogMapper cabalPrizeDrawLogMapper;

    @Resource
    private CabalPickUpItemConfigMapper cabalPickUpItemConfigMapper;

    private static String PRIZE_DRAW_ITEM_CONTENT = "$48#【温馨提示】$34#中奖物品$7#[%s]$34#已发送至元宝背包，请打开元宝背包领取";

    @Override
    public String mallShopBuyItems(CabalMallBuyItemDTO cabalMallBuyItemDTO) {
        String resultMessage = "SUCCESS";
        try {
            Integer itemIdx = cabalMallBuyItemDTO.getItemIdx();
            // 根据itemIdx查询商品上架商品信息
            CabalMallSellItem cabalMallSellItem = cabalMallSellItemMapper.getCabalMallSellItemById(itemIdx, cabalMallBuyItemDTO.getItemOpt(), cabalMallBuyItemDTO.getCategory());
            if(cabalMallSellItem == null) {
                resultMessage = "请勿非法操作";
                return resultMessage;
            }

            Integer buyResult;
            if(cabalMallSellItem.getCategory() == 9) {
                buyResult = buyHandlerByContributePoint(cabalMallSellItem, cabalMallBuyItemDTO);
            } else {
                buyResult = buyHandler(cabalMallSellItem, cabalMallBuyItemDTO);
            }

            if(buyResult == 0) {
                resultMessage = "呵呵，余额不足";
                return resultMessage;
            }

            if(itemIdx == 10000) { // 充值GM BUFF
                // 查询在线角色信息
                int iUserNum = cabalMallBuyItemDTO.getUserNum();
                int startCharacterId = iUserNum * 8;
                int endCharacterId = startCharacterId + 5;

                CabalCharacter cabalCharacter = cabalAuthMapper.getCabalCharacterByCharacterId(startCharacterId, endCharacterId);
                CabalCharacterGmBuffDTO cabalCharacterGmBuffDTO = new CabalCharacterGmBuffDTO();
                cabalCharacterGmBuffDTO.setCharacterIdx(String.valueOf(cabalCharacter.getCharacterIdx()));
                cabalCharacterGmBuffDTO.setDays(String.valueOf(cabalMallBuyItemDTO.getItemOpt()));
                this.rechargeGmBuff(cabalCharacterGmBuffDTO);
            } else {
                sendItems(cabalMallSellItem, cabalMallBuyItemDTO);
            }
        } catch (Exception e) {
            log.error("发送商城币失败", e);
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }

        return resultMessage;
    }

    @Transactional
    protected int buyHandlerByContributePoint(CabalMallSellItem cabalMallSellItem, CabalMallBuyItemDTO cabalMallBuyItemDTO) {
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        try {
            // 插入购买记录
            long eventId = insertCabalMallBuyRecord(cabalMallSellItem, cabalMallBuyItemDTO, 2);

            // 查询当前玩家的贡献积分
            Integer userNum = cabalMallBuyItemDTO.getUserNum();
            QueryWrapper<CabalContributePointAccount> queryWrapper = new QueryWrapper<CabalContributePointAccount>();
            queryWrapper.lambda().eq(CabalContributePointAccount::getUserNum, userNum);
            CabalContributePointAccount cabalContributePointAccount =  cabalContributePointAccountMapper.selectOne(queryWrapper);

            if(cabalContributePointAccount == null) {
                return 0 ;
            }

            // 新增贡献积分日志
            Integer mallCoinAfter = insertCabalContributePointLog(cabalMallSellItem, cabalMallBuyItemDTO, cabalContributePointAccount);
            if(mallCoinAfter == 0) {
                return mallCoinAfter;
            }

            // 修改帐号贡献积分
            CabalContributePointAccount updateCabalContributePointAccount = new CabalContributePointAccount();
            updateCabalContributePointAccount.setId(cabalContributePointAccount.getId());
            updateCabalContributePointAccount.setContributePoint(mallCoinAfter);
            updateCabalContributePointAccount.setUpdateTime(new Timestamp(new Date().getTime()));
            cabalContributePointAccountMapper.updateById(updateCabalContributePointAccount);
        } catch (Exception e) {
            log.error("｛｝购买商品发生异常>>>>", cabalMallBuyItemDTO.getUserNum(), e);
            throw new TmsServiceException(ErrorCodeEnum.SYSTOM_ERROR,"购买商品出错，请联系管理员");
        } finally {
            // 执行物品发送存储过程
            DynamicDataSourceContextHolder.removeContextKey();
        }
        return 1;
    }

    private Integer insertCabalContributePointLog(CabalMallSellItem cabalMallSellItem,
                                                  CabalMallBuyItemDTO cabalMallBuyItemDTO,
                                                  CabalContributePointAccount cabalContributePointAccount) {
        // 判断余额是否够买
        Integer unitPrice = cabalMallSellItem.getUnitPrice();
        Integer totalPrice = unitPrice * cabalMallBuyItemDTO.getBuyQty();
        if(cabalContributePointAccount.getContributePoint() < totalPrice) {
            return 0;
        }

        CabalContributePointLog cabalContributePointLog = new CabalContributePointLog();
        cabalContributePointLog.setUserNum(cabalContributePointAccount.getUserNum());
        cabalContributePointLog.setChangePoint(0 - cabalMallSellItem.getUnitPrice() * cabalMallBuyItemDTO.getBuyQty());
        cabalContributePointLog.setEventType(3);
        cabalContributePointLog.setAccount(cabalContributePointAccount.getAccount());
        return cabalContributePointService.insertCabalContributePointLog(cabalContributePointLog);
    }


    @Transactional
    protected int buyHandler(CabalMallSellItem cabalMallSellItem, CabalMallBuyItemDTO cabalMallBuyItemDTO) {
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        try {
            // 插入购买记录
            long eventId = insertCabalMallBuyRecord(cabalMallSellItem, cabalMallBuyItemDTO, 1);

            // 新增商城币日志
            Integer mallCoinAfter = insertCabalMallCoinLog(cabalMallSellItem, cabalMallBuyItemDTO, eventId);
            if(mallCoinAfter == 0) {
                return mallCoinAfter;
            }

            // 修改帐号商城币余额
            cabalMallCoinAccountMapper.updateMallCoinAccount(mallCoinAfter, cabalMallBuyItemDTO.getUserNum());

            // 执行物品发送存储过程
            DynamicDataSourceContextHolder.removeContextKey();

        } catch (Exception e) {
            log.error("｛｝购买商品发生异常>>>>", cabalMallBuyItemDTO.getUserNum(), e);
            throw new TmsServiceException(ErrorCodeEnum.SYSTOM_ERROR,"购买商品出错，请联系管理员");
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }
        return 1;
    }

    private long insertCabalMallBuyRecord(CabalMallSellItem cabalMallSellItem, CabalMallBuyItemDTO cabalMallBuyItemDTO, Integer alaType) {
        CabalMallBuyRecord cabalMallBuyRecord = new CabalMallBuyRecord();
        cabalMallBuyRecord.setId(SnowflakeIdUtil.getInstance().nextId());
        cabalMallBuyRecord.setUserNum(cabalMallBuyItemDTO.getUserNum());
        cabalMallBuyRecord.setAlzType(alaType);
        cabalMallBuyRecord.setBuyItemKindIdx(cabalMallBuyItemDTO.getItemIdx());
        cabalMallBuyRecord.setBuyItemOpt(cabalMallSellItem.getItemOpt());
        cabalMallBuyRecord.setBuyQty(cabalMallBuyItemDTO.getBuyQty());
        cabalMallBuyRecord.setBuyTotalPrice(cabalMallSellItem.getUnitPrice() * cabalMallBuyItemDTO.getBuyQty());
        cabalMallBuyRecord.setCreateTime(new Timestamp(new Date().getTime()));
        cabalMallBuyRecord.setItemName(cabalMallSellItem.getItemName());
        cabalMallBuyRecordMapper.insert(cabalMallBuyRecord);
        return cabalMallBuyRecord.getId();
    }

    private Integer insertCabalMallCoinLog(CabalMallSellItem cabalMallSellItem, CabalMallBuyItemDTO cabalMallBuyItemDTO, long eventId) {
        // 查询当前玩家的商城币信息
        QueryWrapper<CabalMallCoinAccount> queryWrapper = new QueryWrapper<CabalMallCoinAccount>();
        queryWrapper.lambda().eq(CabalMallCoinAccount::getUserNum, cabalMallBuyItemDTO.getUserNum());
        CabalMallCoinAccount cabalMallCoinAccount =  cabalMallCoinAccountMapper.selectOne(queryWrapper);

        if(cabalMallCoinAccount == null) {
            return 0 ;
        }

        // 判断余额是否够买
        Integer unitPrice = cabalMallSellItem.getUnitPrice();
        Integer totalPrice = unitPrice * cabalMallBuyItemDTO.getBuyQty();
        if(cabalMallCoinAccount.getMallCoinTotal() < totalPrice) {
            return 0;
        }

        CabalMallCoinLog cabalMallCoinLog = new CabalMallCoinLog();
        cabalMallCoinLog.setChangeMallCoin(0 - cabalMallSellItem.getUnitPrice() * cabalMallBuyItemDTO.getBuyQty());
        cabalMallCoinLog.setEventId(eventId);
        cabalMallCoinLog.setLogDateTime(new Timestamp(new Date().getTime()));
        cabalMallCoinLog.setLogType(1);
        cabalMallCoinLog.setMallCoinAfter(cabalMallCoinAccount.getMallCoinTotal() + cabalMallCoinLog.getChangeMallCoin());
        cabalMallCoinLog.setId(SnowflakeIdUtil.getInstance().nextId());
        cabalMallCoinLog.setMallCoinPre(cabalMallCoinAccount.getMallCoinTotal());
        cabalMallCoinLog.setUserNum(cabalMallBuyItemDTO.getUserNum());
        cabalMallCoinLogMapper.insert(cabalMallCoinLog);

        return cabalMallCoinLog.getMallCoinAfter();
    }

    private void sendItems(CabalMallSellItem cabalMallSellItem, CabalMallBuyItemDTO cabalMallBuyItemDTO) {
        Map<String, Object> sendItemParams = new HashMap<>();
        for(int i = 0; i < cabalMallBuyItemDTO.getBuyQty(); i++) {
            sendItemParams.put("itemIdx", cabalMallSellItem.getItemKindIdx());
            sendItemParams.put("itemOpt", cabalMallSellItem.getItemOpt());
            sendItemParams.put("durationIdx", cabalMallSellItem.getDurationIdx());
            sendItemParams.put("userNum", cabalMallBuyItemDTO.getUserNum());
            cabalAuthMapper.execSendItemByItemId(sendItemParams);
        }
    }

    @Override
    public void initMallItems(List<String> itemList, Integer category) {
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        for(String strItem : itemList) {
            String[] arrItem = strItem.split("\\|");
            String strItemIdx = arrItem[0];
            Integer itemIdx;
            Integer itemOpt = 0;
            if(strItemIdx.contains("-")) {
                String[] arrTmp = strItemIdx.split("-");
                itemIdx = Integer.parseInt(arrTmp[0]);
                itemOpt = Integer.parseInt(arrTmp[1]);
            } else {
                itemIdx = Integer.parseInt(strItemIdx);
            }
            String itemName = arrItem[1];

            CabalMallSellItem cabalMallSellItem = new CabalMallSellItem();
            cabalMallSellItem.setId(SnowflakeIdUtil.getInstance().nextId());
            cabalMallSellItem.setAlzType(1);
            cabalMallSellItem.setAvailable(1);
            cabalMallSellItem.setCategory(category);
            cabalMallSellItem.setCreateTime(new Timestamp(new Date().getTime()));
            cabalMallSellItem.setDurationIdx(0);
            cabalMallSellItem.setIconName("N");
            String itemDesc = "";
            /*if(itemName.contains("发型")) {
                itemDesc = "变更角色发型的工具";
            } else if(itemName.contains("脸型")) {
                itemDesc = "变更角色脸型的工具";
            }*/
            cabalMallSellItem.setItemDesc(itemDesc);
            cabalMallSellItem.setItemKindIdx(itemIdx);
            cabalMallSellItem.setItemOpt(itemOpt);
            cabalMallSellItem.setUnitPrice(100);
            cabalMallSellItem.setItemName(itemName);
            cabalMallSellItemMapper.insert(cabalMallSellItem);
        }
    }

    @Override
    public void sendMallCoin(String account, String mallCoin) {
        Long eventId = SnowflakeIdUtil.getInstance().nextId();
        if(StringUtils.isNotBlank(account)) {
            handMallCoin(account, mallCoin, eventId);
            return;
        }

        // 查询account_list表给所有帐号发送商城币
        List<String> accountList = cabalAuthMapper.searchAccountList();
        if (CollectionUtils.isEmpty(accountList)) return;

        for(String inAccount : accountList) {
            handMallCoin(inAccount, mallCoin, eventId);
        }
    }

    private void handMallCoin(String account, String mallCoin, Long eventId) {
        try {
            // 查询帐号信息
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_ACCOUNT);
            CabalAuthVo cabalAuthVo = cabalAuthMapper.getCabalAuthVoByAccount(account);
            if (cabalAuthVo == null) {
                log.info("{}帐号不存在", account);
                return;
            }

            Integer userNum = cabalAuthVo.getUserNum();

            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            // 新增充值记录
            insertCabalMallCoinLog(userNum, mallCoin, eventId);

            // 修改帐号商城币余额
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            updateAccountCash(userNum, mallCoin);
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }

    }

    private void insertCabalMallCoinLog(Integer userNum, String mallCoin, long eventId) {
        int intMallCoin = Integer.parseInt(mallCoin);
        CabalMallCoinLog cabalMallCoinLog = new CabalMallCoinLog();
        cabalMallCoinLog.setChangeMallCoin(intMallCoin);
        cabalMallCoinLog.setEventId(eventId);
        cabalMallCoinLog.setLogDateTime(new Timestamp(new Date().getTime()));
        // 赠送
        cabalMallCoinLog.setLogType(3);
        cabalMallCoinLog.setMallCoinAfter(intMallCoin);
        cabalMallCoinLog.setId(SnowflakeIdUtil.getInstance().nextId());
        cabalMallCoinLog.setMallCoinPre(0);
        cabalMallCoinLog.setUserNum(userNum);
        cabalMallCoinLogMapper.insert(cabalMallCoinLog);
    }

    private void updateAccountCash(Integer userNum, String mallCoin) {
        int diffMin = Integer.parseInt(mallCoin);

        // 查询数据库是否存在对应userNum的记录
        QueryWrapper<CabalMallCoinAccount> queryWrapper = new QueryWrapper<CabalMallCoinAccount>();
        queryWrapper.lambda().eq(CabalMallCoinAccount::getUserNum, userNum);
        CabalMallCoinAccount cabalMallCoinAccount =  cabalMallCoinAccountMapper.selectOne(queryWrapper);
        if(cabalMallCoinAccount == null) {
            CabalMallCoinAccount newCabalMallCoinAccount = new CabalMallCoinAccount();
            newCabalMallCoinAccount.setId(SnowflakeIdUtil.getInstance().nextId());
            newCabalMallCoinAccount.setMallCoinTotal(diffMin);
            newCabalMallCoinAccount.setUserNum(userNum);
            newCabalMallCoinAccount.setUpdateTime(new Timestamp(new Date().getTime()));
            cabalMallCoinAccountMapper.insert(newCabalMallCoinAccount);
            return;
        }

        cabalMallCoinAccount.setUpdateTime(new Timestamp(new Date().getTime()));
        cabalMallCoinAccount.setMallCoinTotal(cabalMallCoinAccount.getMallCoinTotal() + diffMin);
        cabalMallCoinAccountMapper.updateById(cabalMallCoinAccount);
    }

    @Override
    public List<MallBuyRecordDTO> searchMallBuyRecordList(String userNum) {
        List<MallBuyRecordDTO> mallBuyRecordDTOList = new ArrayList<>();
        try {
            QueryWrapper<CabalMallBuyRecord> queryWrapper = new QueryWrapper<CabalMallBuyRecord>();
            queryWrapper.lambda().eq(CabalMallBuyRecord::getUserNum, userNum);
            queryWrapper.orderByDesc("create_time");
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            List<CabalMallBuyRecord> cabalMallBuyRecordList =  cabalMallBuyRecordMapper.selectList(queryWrapper);
            if(CollectionUtils.isEmpty(cabalMallBuyRecordList)) {
                return mallBuyRecordDTOList;
            }


            for(CabalMallBuyRecord cabalMallBuyRecord : cabalMallBuyRecordList) {
                MallBuyRecordDTO mallBuyRecordDTO = new MallBuyRecordDTO();
                BeanUtils.copyProperties(cabalMallBuyRecord, mallBuyRecordDTO);
                mallBuyRecordDTO.setCreateTime(DateApiUtil.format(cabalMallBuyRecord.getCreateTime(), DateApiUtil.NORM_DATETIME_PATTERN));
                mallBuyRecordDTOList.add(mallBuyRecordDTO);
            }
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }

        return mallBuyRecordDTOList;
    }

    @Override
    public List<MallSellItemDTO> searchMallSellItemList(String category) {
        List<MallSellItemDTO> mallSellItemDTOList = new ArrayList<>();
        try {
            QueryWrapper<CabalMallSellItem> queryWrapper = new QueryWrapper<CabalMallSellItem>();
            queryWrapper.lambda().eq(CabalMallSellItem::getCategory, Integer.parseInt(category));
            queryWrapper.orderByDesc("sort_no");
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            List<CabalMallSellItem> cabalMallSellItemList =  cabalMallSellItemMapper.selectList(queryWrapper);
            if(CollectionUtils.isEmpty(cabalMallSellItemList)) {
                return mallSellItemDTOList;
            }


            for(CabalMallSellItem cabalMallSellItem : cabalMallSellItemList) {
                MallSellItemDTO mallSellItemDTO = new MallSellItemDTO();
                BeanUtils.copyProperties(cabalMallSellItem, mallSellItemDTO);
                mallSellItemDTO.setCreateTime(DateApiUtil.format(cabalMallSellItem.getCreateTime(), DateApiUtil.NORM_DATETIME_PATTERN));
                mallSellItemDTOList.add(mallSellItemDTO);
            }
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }

        return mallSellItemDTOList;
    }

    @Override
    public String rechargeGmBuff(CabalCharacterGmBuffDTO cabalCharacterGmBuffDTO) {
        DynamicDataSourceContextHolder.removeContextKey();
        String account = cabalCharacterGmBuffDTO.getAccount();
        CabalAuthVo  cabalAuthVo = cabalAuthMapper.getCabalAuthVoByAccount(account);
        Integer userNum;
        if(StringUtils.isBlank(account)) {
            userNum = Integer.parseInt(cabalCharacterGmBuffDTO.getCharacterIdx()) / 8;
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_ACCOUNT);
            account = cabalAuthMapper.getCabalAuthVoByUserNum(userNum).getUserId();
        } else {
            userNum = cabalAuthVo.getUserNum();
        }

        String updateHex = gmBuffHex;
        byte[] updateBytes = HighLowSwapUtil.hexStringToByteArray(updateHex);
        QueryWrapper<CabalCharacterGmBuff> queryWrapper = new QueryWrapper<CabalCharacterGmBuff>();
        queryWrapper.lambda().eq(CabalCharacterGmBuff::getAccount, account);
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        CabalCharacterGmBuff dbCabalCharacterGmBuff = cabalCharacterGmBuffMapper.selectOne(queryWrapper);
        if(dbCabalCharacterGmBuff == null) {
            // 1、新增过期时间记录
            CabalCharacterGmBuff cabalCharacterGmBuff = new CabalCharacterGmBuff();
            cabalCharacterGmBuff.setAccount(cabalCharacterGmBuffDTO.getAccount());
            cabalCharacterGmBuff.setCreateTime(new Timestamp(new Date().getTime()));
            cabalCharacterGmBuff.setGmBuff(updateBytes);
            cabalCharacterGmBuff.setUserNum(userNum);
            cabalCharacterGmBuff.setAccount(account);

            // 计算过期时间
            Date expirationDate = DateApiUtil.offSiteDate(new Date(), Calendar.DAY_OF_YEAR, Integer.parseInt(cabalCharacterGmBuffDTO.getDays()));
            cabalCharacterGmBuff.setExpirationDate(expirationDate);
            cabalCharacterGmBuffMapper.insert(cabalCharacterGmBuff);
        } else {
            Date expirationDate = dbCabalCharacterGmBuff.getExpirationDate();
            Date nowDate = new Date();
            // 判断过期时间是否大于当前时间，如果大于则直接追加充值时间，如果小于则表明已经过期，那么直接取当前日期充值
            if(nowDate.before(expirationDate)) {
                expirationDate = DateApiUtil.offSiteDate(expirationDate, Calendar.DAY_OF_YEAR, Integer.parseInt(cabalCharacterGmBuffDTO.getDays()));
            } else {
                expirationDate = DateApiUtil.offSiteDate(nowDate, Calendar.DAY_OF_YEAR, Integer.parseInt(cabalCharacterGmBuffDTO.getDays()));
            }
            dbCabalCharacterGmBuff.setExpirationDate(expirationDate);
            dbCabalCharacterGmBuff.setUpdateTime(new Timestamp(new Date().getTime()));
            cabalCharacterGmBuffMapper.updateById(dbCabalCharacterGmBuff);
        }

        /*DynamicDataSourceContextHolder.removeContextKey();
        // 2、同步修改对应角色BUFF
        if(cabalAuthVo == null) {
            return "SUCCESS";
        }

        int iUserNum = cabalAuthVo.getUserNum();
        int characterId = iUserNum * 8;
        for(int i = 0; i < 6; i++) {
            updateCharacterGmBuff(characterId);
            characterId ++;
        }*/

        return "SUCCESS";
    }

    private void updateCharacterGmBuff(int characterId) {
        CabalSkillData cabalSkillData = cabalAuthMapper.getCabalSkillData(characterId);
        String hexResult = HighLowSwapUtil.byteToHex(cabalSkillData.getSkillData());
        String updateHex = hexResult.concat(gmBuffHex);
        byte[] updateBytes = HighLowSwapUtil.hexStringToByteArray(updateHex);
        cabalAuthMapper.updateSkillData(characterId, updateBytes);
    }

    @Override
    public void checkGmBuffJob() {
        // 查询过期时间小于当前时间的集合
        LambdaQueryWrapper<CabalCharacterGmBuff> queryWrapper = new QueryWrapper<CabalCharacterGmBuff>().lambda();
        queryWrapper.le(CabalCharacterGmBuff::getExpirationDate, new Date());
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        List<CabalCharacterGmBuff> cabalCharacterGmBuffList = cabalCharacterGmBuffMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(cabalCharacterGmBuffList)) {
            String updateHex = "";
            byte[] updateBytes = HighLowSwapUtil.hexStringToByteArray(updateHex);
            List<CabalUpdateSavedBuff> updateCabalUpdateSavedBuffList = new ArrayList<>();
            List<Long> idList = new ArrayList<>();
            for(CabalCharacterGmBuff cabalCharacterGmBuff : cabalCharacterGmBuffList) {
                CabalUpdateSavedBuff cabalUpdateSavedBuff = new CabalUpdateSavedBuff();
                cabalUpdateSavedBuff.setCharacterId(cabalCharacterGmBuff.getCharacterId());
                cabalUpdateSavedBuff.setInitBuff(updateBytes);
                updateCabalUpdateSavedBuffList.add(cabalUpdateSavedBuff);
                idList.add(cabalCharacterGmBuff.getId());
            }

            cabalCharacterGmBuffMapper.deleteBatchIds(idList);

            cabalCharacterGmBuffMapper.batchInitGmBuff(updateCabalUpdateSavedBuffList);
        }

        // 查询未过期GM BUFF角色集合
        LambdaQueryWrapper<CabalCharacterGmBuff> queryBuffWrapper = new QueryWrapper<CabalCharacterGmBuff>().lambda();
        queryBuffWrapper.ge(CabalCharacterGmBuff::getExpirationDate, new Date());
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        cabalCharacterGmBuffList = cabalCharacterGmBuffMapper.selectList(queryBuffWrapper);
        log.info("查询到未过期账号>>>>{}", cabalCharacterGmBuffList.size());
        if(CollectionUtils.isEmpty(cabalCharacterGmBuffList)) {
            return;
        }

        /*byte[] updateBytes = HighLowSwapUtil.hexStringToByteArray(gmBuffHex);
        for(CabalCharacterGmBuff cabalCharacterGmBuff : cabalCharacterGmBuffList) {
            log.info("角色{}执行更新BUFF操作", cabalCharacterGmBuff.getCharacterId());
            cabalAuthMapper.updateSavedGmBuff(cabalCharacterGmBuff.getCharacterId(), updateBytes);
        }*/

    }

    @Override
    public List<MallSellItemDTO> searchItemListByKeyword(String itemNameKeyword) {
        List<MallSellItemDTO> mallSellItemDTOList = new ArrayList<>();
        try {
            QueryWrapper<CabalMallSellItem> queryWrapper = new QueryWrapper<CabalMallSellItem>();
            queryWrapper.lambda().like(CabalMallSellItem::getItemName, itemNameKeyword);
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            List<CabalMallSellItem> cabalMallSellItemList =  cabalMallSellItemMapper.selectList(queryWrapper);
            if(CollectionUtils.isEmpty(cabalMallSellItemList)) {
                return mallSellItemDTOList;
            }


            for(CabalMallSellItem cabalMallSellItem : cabalMallSellItemList) {
                MallSellItemDTO mallSellItemDTO = new MallSellItemDTO();
                BeanUtils.copyProperties(cabalMallSellItem, mallSellItemDTO);
                mallSellItemDTO.setCreateTime(DateApiUtil.format(cabalMallSellItem.getCreateTime(), DateApiUtil.NORM_DATETIME_PATTERN));
                mallSellItemDTOList.add(mallSellItemDTO);
            }
        } finally {
            DynamicDataSourceContextHolder.removeContextKey();
        }

        return mallSellItemDTOList;
    }

    @Override
    public String updateShopState(UpdateShopStateDTO updateShopStateDTO) {
        DynamicDataSourceContextHolder.removeContextKey();
        CabalAuthVo  cabalAuthVo = cabalAuthMapper.getCabalAuthVoByAccount(updateShopStateDTO.getAccount());
        if(cabalAuthVo == null) {
            return "SUCCESS";
        }

        // 查询在线角色信息
        int iUserNum = cabalAuthVo.getUserNum();
        int startCharacterId = iUserNum * 8;
        int endCharacterId = startCharacterId + 5;
        CabalCharacter cabalCharacter = cabalAuthMapper.getCabalCharacterByCharacterId(startCharacterId, endCharacterId);
        if(cabalCharacter != null) {
            int characterIdx = cabalCharacter.getCharacterIdx();
            QueryWrapper<CabalCharacterInfo> queryWrapper = new QueryWrapper<CabalCharacterInfo>();
            queryWrapper.lambda().eq(CabalCharacterInfo::getCharacterId, characterIdx);
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            int count = cabalCharacterInfoMapper.selectCount(queryWrapper);
            if(count == 0) {
                CabalCharacterInfo insertCabalCharacterInfo = new CabalCharacterInfo();
                insertCabalCharacterInfo.setCharacterId(characterIdx);
                insertCabalCharacterInfo.setShopState(Integer.parseInt(updateShopStateDTO.getShopState()));
                cabalCharacterInfoMapper.insert(insertCabalCharacterInfo);
            } else {
                CabalCharacterInfo updateCabalCharacterInfo = new CabalCharacterInfo();
                updateCabalCharacterInfo.setCharacterId(characterIdx);
                updateCabalCharacterInfo.setShopState(Integer.parseInt(updateShopStateDTO.getShopState()));
                cabalCharacterInfoMapper.updateById(updateCabalCharacterInfo);
            }
        }
        DynamicDataSourceContextHolder.removeContextKey();
        return "SUCCESS";
    }

    @Override
    public List<CabalAvatarItemDTO> selectGarmentCallInfoList(String account) {
        QueryWrapper<CabalAvatarItem> queryWrapper = new QueryWrapper<CabalAvatarItem>();
        queryWrapper.lambda().eq(CabalAvatarItem::getAvatarType, "7");
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        List<CabalAvatarItem> cabalAvatarItemList = cabalAvatarItemMapper.selectList(queryWrapper);
        List<CabalAvatarItemDTO> cabalAvatarItemDTOList = new ArrayList<>();
        for(CabalAvatarItem cabalAvatarItem : cabalAvatarItemList) {
            CabalAvatarItemDTO cabalAvatarItemDTO = new CabalAvatarItemDTO();
            BeanUtils.copyProperties(cabalAvatarItem, cabalAvatarItemDTO);
            cabalAvatarItemDTO.setAvatarType(String.valueOf(cabalAvatarItem.getAvatarType()));
            cabalAvatarItemDTOList.add(cabalAvatarItemDTO);
        }
        return cabalAvatarItemDTOList;
    }

    @Override
    public List<WeaponAvatarItemDTO> selectWeaponCallInfoList(String userNum) {
        if(StringUtils.isBlank(userNum)) {
            new ArrayList<>();
        }
        List<WeaponAvatarItemDTO> weaponAvatarItemDTOList = new ArrayList<>();

        int iUserNum = Integer.parseInt(userNum);
        int startCharacterId = iUserNum * 8;
        int endCharacterId = startCharacterId + 5;

        CabalCharacter cabalCharacter = cabalAuthMapper.getCabalCharacterByCharacterId(startCharacterId, endCharacterId);
        int classType = cabalCharacter.getProfession();

        // 根据职业查询武器装饰
        QueryWrapper<CabalAvatarItem> queryWrapper = new QueryWrapper<CabalAvatarItem>();
        queryWrapper.lambda().eq(CabalAvatarItem::getClassType, classType);
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        List<CabalAvatarItem> cabalAvatarItemList = cabalAvatarItemMapper.selectList(queryWrapper);

        // 然后根据itemId进行分组
        Map<String, List<CabalAvatarItemDTO>> itemMap = new HashMap<>();
        for(CabalAvatarItem cabalAvatarItem : cabalAvatarItemList) {
            String itemId = cabalAvatarItem.getItemId().toString();
            CabalAvatarItemDTO cabalAvatarItemDTO = new CabalAvatarItemDTO();
            BeanUtils.copyProperties(cabalAvatarItem, cabalAvatarItemDTO);
            cabalAvatarItemDTO.setItemId(itemId);
            if(itemMap.containsKey(itemId)) {
                List<CabalAvatarItemDTO> cabalAvatarItems = itemMap.get(itemId);
                cabalAvatarItems.add(cabalAvatarItemDTO);
                itemMap.put(itemId, cabalAvatarItems);
            } else {
                List<CabalAvatarItemDTO> cabalAvatarItems = new ArrayList<>();
                cabalAvatarItems.add(cabalAvatarItemDTO);
                itemMap.put(itemId, cabalAvatarItems);
            }
        }

        for (Map.Entry<String, List<CabalAvatarItemDTO>> entry : itemMap.entrySet()) {
            String key = entry.getKey();
            List<CabalAvatarItemDTO> value = entry.getValue();
            WeaponAvatarItemDTO weaponAvatarItemDTO = new WeaponAvatarItemDTO();
            weaponAvatarItemDTO.setItemId(key);
            weaponAvatarItemDTO.setCabalAvatarItemList(value);
            weaponAvatarItemDTOList.add(weaponAvatarItemDTO);
        }
        return weaponAvatarItemDTOList;
    }

    @Override
    public List<CabalAvatarItemDTO> selectHeadWearCallInfoList(String account) {
        QueryWrapper<CabalAvatarItem> queryWrapper = new QueryWrapper<CabalAvatarItem>();
        queryWrapper.lambda().eq(CabalAvatarItem::getAvatarType, "0");
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        List<CabalAvatarItem> cabalAvatarItemList = cabalAvatarItemMapper.selectList(queryWrapper);
        List<CabalAvatarItemDTO> cabalAvatarItemDTOList = new ArrayList<>();
        for(CabalAvatarItem cabalAvatarItem : cabalAvatarItemList) {
            CabalAvatarItemDTO cabalAvatarItemDTO = new CabalAvatarItemDTO();
            BeanUtils.copyProperties(cabalAvatarItem, cabalAvatarItemDTO);
            cabalAvatarItemDTO.setAvatarType(String.valueOf(cabalAvatarItem.getAvatarType()));
            cabalAvatarItemDTOList.add(cabalAvatarItemDTO);
        }
        return cabalAvatarItemDTOList;
    }

    @Override
    public String checkGmBuff(String account) {
        QueryWrapper<CabalCharacterGmBuff> queryWrapper = new QueryWrapper<CabalCharacterGmBuff>();
        queryWrapper.lambda().eq(CabalCharacterGmBuff::getAccount, account);
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        int count = cabalCharacterGmBuffMapper.selectCount(queryWrapper);
        if(count < 1) {
            return "FAIL";
        }
        return "SUCCESS";
    }

    @Override
    public String getWarpIdByDungeonTargetId(String dungeonTargetPreId, String dungeonTargetBackId) {
        QueryWrapper<CabalDungeonWarpIdConfig> queryWrapper = new QueryWrapper<CabalDungeonWarpIdConfig>();
        queryWrapper.lambda().eq(CabalDungeonWarpIdConfig::getDungeonPreId, Integer.parseInt(dungeonTargetPreId));
        queryWrapper.lambda().eq(CabalDungeonWarpIdConfig::getDungeonBackId, Integer.parseInt(dungeonTargetBackId));
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        CabalDungeonWarpIdConfig cabalDungeonWarpIdConfig = cabalDungeonWarpIdConfigMapper.selectOne(queryWrapper);
        if(cabalDungeonWarpIdConfig != null) {
            return cabalDungeonWarpIdConfig.getWarpId();
        }
        return "";
    }

    @Override
    public void initEquipmentSellConfig(List<String> itemList, Integer itemType) {
        for(String strItem : itemList) {
            String[] arrItem = strItem.split("\\|");
            Integer itemIdx = Integer.parseInt(arrItem[0]);
            Integer itemOpt = Integer.parseInt(arrItem[1]);

            CabalEquipmentSellConfig cabalEquipmentSellConfig = new CabalEquipmentSellConfig();
            cabalEquipmentSellConfig.setItemIdx(itemIdx);
            cabalEquipmentSellConfig.setItemOpt(itemOpt);
            cabalEquipmentSellConfig.setItemType(6);
            DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
            cabalEquipmentSellConfigMapper.insert(cabalEquipmentSellConfig);
        }

    }

    @Override
    public void initEventData(Integer itemType) {
        QueryWrapper<CabalEquipmentSellConfig> queryWrapper = new QueryWrapper<CabalEquipmentSellConfig>();
        queryWrapper.lambda().eq(CabalEquipmentSellConfig::getItemType, itemType);
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        List<CabalEquipmentSellConfig> cabalEquipmentSellConfigList = cabalEquipmentSellConfigMapper.selectList(queryWrapper);

        int slotIdx = 0;
        int itemPriceId = 135;
        int index = 0;
        for(CabalEquipmentSellConfig cabalEquipmentSellConfig : cabalEquipmentSellConfigList) {
            ++index;
            CabalEmsEventNpcItemShop cabalEmsEventNpcItemShop = new CabalEmsEventNpcItemShop();
            cabalEmsEventNpcItemShop.setEventId(cabalEquipmentSellConfig.getItemType());
            if(index == 6) {
                slotIdx = slotIdx + 3;
                index = 1;
            }
            cabalEmsEventNpcItemShop.setSlotIdx(slotIdx);

            cabalEmsEventNpcItemShop.setItemKindIdx(2842);
            int itemOpt = 0;
            if(cabalEquipmentSellConfig.getPriceLevel() == 4) {
                itemOpt = 5000000;
            }
            if(cabalEquipmentSellConfig.getPriceLevel() == 3) {
                itemOpt = 3000000;
            }
            if(cabalEquipmentSellConfig.getPriceLevel() == 2) {
                itemOpt = 2500000;
            }
            if(cabalEquipmentSellConfig.getPriceLevel() == 1) {
                itemOpt = 2000000;
            }
            cabalEmsEventNpcItemShop.setItemOption(itemOpt);
            cabalEmsEventNpcItemShop.setItemPriceId(itemPriceId);

            //cabalEmsEventNpcItemMapper.insert(cabalEmsEventNpcItemShop);

            CabalEmsEventNpcItemPrice cabalEmsEventNpcItemPrice = new CabalEmsEventNpcItemPrice();
            cabalEmsEventNpcItemPrice.setItemKindIdx(cabalEquipmentSellConfig.getItemIdx());
            cabalEmsEventNpcItemPrice.setItemOption(cabalEquipmentSellConfig.getItemOpt());
            cabalEmsEventNpcItemPrice.setItemPriceId(itemPriceId);
            cabalEmsEventNpcItemPriceMapper.insert(cabalEmsEventNpcItemPrice);

            slotIdx ++;
            itemPriceId++;



        }

    }

    @Override
    public String deductMallCoinHandle(String account, String deductType) {
        if("0".equals(account)) {
            account = "test5";
        }

        try {
            DynamicDataSourceContextHolder.removeContextKey();
            CabalAuthVo cabalAuthVo = cabalAuthMapper.getCabalAuthVoByAccount(account);

            if(cabalAuthVo == null) {
                return "FAIL";
            }

            if("1".equals(deductType)) {
                CabalMallSellItem cabalMallSellItem = new CabalMallSellItem();
                cabalMallSellItem.setItemName("麒麟幸运九宫格");
                cabalMallSellItem.setUnitPrice(100);
                cabalMallSellItem.setItemOpt(0);
                cabalMallSellItem.setItemKindIdx(20000);
                cabalMallSellItem.setDurationIdx(0);
                cabalMallSellItem.setAlzType(1);

                CabalMallBuyItemDTO cabalMallBuyItemDTO = new CabalMallBuyItemDTO();
                cabalMallBuyItemDTO.setBuyQty(1);
                cabalMallBuyItemDTO.setCategory(50);
                cabalMallBuyItemDTO.setItemIdx(20000);
                cabalMallBuyItemDTO.setItemOpt(0);
                cabalMallBuyItemDTO.setUserNum(cabalAuthVo.getUserNum());
                Integer buyResult = buyHandlerByContributePoint(cabalMallSellItem, cabalMallBuyItemDTO);
                if(buyResult == 0) {
                    return "FAIL";
                }
            }
        } catch (Exception e) {
            log.error("{}-麒麟幸运九宫格扣除贡献积分出错", account, e);
            return "贡献积分余额不足或扣除失败";
        }

        return "SUCCESS";
    }

    @Override
    public String getPrizeDrawCount(String account) {
        if("0".equals(account)) {
            account = "test5";
        }

        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);

        QueryWrapper<CabalPrizeDrawAccount> queryWrapper = new QueryWrapper<CabalPrizeDrawAccount>();
        queryWrapper.lambda().eq(CabalPrizeDrawAccount::getAccount, account);
        CabalPrizeDrawAccount cabalPrizeDrawAccount = cabalPrizeDrawAccountMapper.selectOne(queryWrapper);

        String count;
        if(cabalPrizeDrawAccount == null) {
            CabalPrizeDrawAccount insertCabalPrizeDrawAccount = new CabalPrizeDrawAccount();
            insertCabalPrizeDrawAccount.setId(SnowflakeIdUtil.getInstance().nextId());
            insertCabalPrizeDrawAccount.setAccount(account);
            insertCabalPrizeDrawAccount.setCount(5);
            insertCabalPrizeDrawAccount.setVipCount(5);
            insertCabalPrizeDrawAccount.setCreateTime(new Timestamp(new Date().getTime()));
            cabalPrizeDrawAccountMapper.insert(insertCabalPrizeDrawAccount);
            count = "5";
        } else {
            count = cabalPrizeDrawAccount.getCount().toString();
        }
        DynamicDataSourceContextHolder.removeContextKey();
        return count;
    }

    @Override
    public String deductPrizeDrawCount(String account) {
        if("0".equals(account)) {
            account = "test5";
        }

        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        QueryWrapper<CabalPrizeDrawAccount> queryWrapper = new QueryWrapper<CabalPrizeDrawAccount>();
        queryWrapper.lambda().eq(CabalPrizeDrawAccount::getAccount, account);
        CabalPrizeDrawAccount cabalPrizeDrawAccount = cabalPrizeDrawAccountMapper.selectOne(queryWrapper);

        if(cabalPrizeDrawAccount.getCount() == 0) {
            return "0";
        }

        CabalPrizeDrawAccount updateCabalPrizeDrawAccount = new CabalPrizeDrawAccount();
        updateCabalPrizeDrawAccount.setCount(cabalPrizeDrawAccount.getCount() - 1);
        updateCabalPrizeDrawAccount.setId(cabalPrizeDrawAccount.getId());
        cabalPrizeDrawAccountMapper.updateById(updateCabalPrizeDrawAccount);
        DynamicDataSourceContextHolder.removeContextKey();
        return updateCabalPrizeDrawAccount.getCount().toString();
    }

    @Override
    @Transactional
    public String recordPrizeDrawLog(String account, String rewardLevel) {
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        CabalPrizeDrawLog cabalPrizeDrawLog = new CabalPrizeDrawLog();
        cabalPrizeDrawLog.setId(SnowflakeIdUtil.getInstance().nextId());
        cabalPrizeDrawLog.setAccount(account);
        cabalPrizeDrawLog.setRewardLevel(Integer.parseInt(rewardLevel));
        cabalPrizeDrawLog.setCreateTime(new Timestamp(new Date().getTime()));

        // 查询奖品配置获取奖品物品信息
        QueryWrapper<CabalLotteryPoolConfig> queryWrapper = new QueryWrapper<CabalLotteryPoolConfig>();
        queryWrapper.lambda().eq(CabalLotteryPoolConfig::getRewardLevel, Integer.parseInt(rewardLevel));
        queryWrapper.lambda().eq(CabalLotteryPoolConfig::getStatus, 1);
        CabalLotteryPoolConfig cabalLotteryPoolConfig = cabalLotteryPoolConfigMapper.selectOne(queryWrapper);
        if(cabalLotteryPoolConfig == null) {
           return "$48#中奖物品发送失败";
        }

        Integer itemIdx = cabalLotteryPoolConfig.getItemIdx();
        Integer itemOpt = cabalLotteryPoolConfig.getItemOpt();
        Integer durationIdx = cabalLotteryPoolConfig.getDurationIdx();
        String itemName = cabalLotteryPoolConfig.getItemName();

        cabalPrizeDrawLog.setItemIdx(itemIdx);
        cabalPrizeDrawLog.setItemOpt(itemOpt);
        cabalPrizeDrawLogMapper.insert(cabalPrizeDrawLog);

        // 发送奖励物品
        DynamicDataSourceContextHolder.removeContextKey();
        CabalAuthVo cabalAuthVo = cabalAuthMapper.getCabalAuthVoByAccount(account);
        Map<String, Object> sendItemParams = new HashMap<>();
        sendItemParams.put("itemIdx", itemIdx);
        sendItemParams.put("itemOpt", itemOpt);
        sendItemParams.put("durationIdx", durationIdx);
        sendItemParams.put("userNum", cabalAuthVo.getUserNum());
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_ACCOUNT);
        cabalAuthMapper.execSendItemByItemId(sendItemParams);

        String sendContent = String.format(PRIZE_DRAW_ITEM_CONTENT, itemName);

        return sendContent;
    }

    @Override
    public CabalLotteryPoolConfigDTO getLotteryPoolConfig() {
        CabalLotteryPoolConfigDTO cabalLotteryPoolConfigDTO = new CabalLotteryPoolConfigDTO();
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        QueryWrapper<CabalLotteryPoolConfig> queryWrapper = new QueryWrapper<CabalLotteryPoolConfig>();
        queryWrapper.lambda().eq(CabalLotteryPoolConfig::getStatus, 1);
        List<CabalLotteryPoolConfig> cabalLotteryPoolConfigList = cabalLotteryPoolConfigMapper.selectList(queryWrapper);
        for(CabalLotteryPoolConfig cabalLotteryPoolConfig : cabalLotteryPoolConfigList) {
            Integer rewardLevel = cabalLotteryPoolConfig.getRewardLevel();
            String itemName = cabalLotteryPoolConfig.getItemName();
            switch (rewardLevel) {
                case 0:
                    cabalLotteryPoolConfigDTO.setLevel0ItemName(itemName);
                    break;
                case 1:
                    cabalLotteryPoolConfigDTO.setLevel1ItemName(itemName);
                    break;
                case 2:
                    cabalLotteryPoolConfigDTO.setLevel2ItemName(itemName);
                    break;
                case 3:
                    cabalLotteryPoolConfigDTO.setLevel3ItemName(itemName);
                    break;
                case 4:
                    cabalLotteryPoolConfigDTO.setLevel4ItemName(itemName);
                    break;
                case 5:
                    cabalLotteryPoolConfigDTO.setLevel5ItemName(itemName);
                    break;
                case 6:
                    cabalLotteryPoolConfigDTO.setLevel6ItemName(itemName);
                    break;
            }

        }
        return cabalLotteryPoolConfigDTO;
    }

    @Override
    public List<CabalPrizeDrawLogDTO> searchCabalPrizeDrawLogList(String userNum) {
        CabalAuthVo cabalAuthVo = cabalAuthMapper.getCabalAuthVoByUserNum(Integer.parseInt(userNum));

        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        QueryWrapper<CabalPrizeDrawLog> queryWrapper = new QueryWrapper<CabalPrizeDrawLog>();
        queryWrapper.lambda().eq(CabalPrizeDrawLog::getAccount, cabalAuthVo.getUserId());
        List<CabalPrizeDrawLog> cabalPrizeDrawLogList = cabalPrizeDrawLogMapper.selectList(queryWrapper);

        List<CabalPrizeDrawLogDTO> cabalPrizeDrawLogDTOList = new ArrayList<>();
        for(CabalPrizeDrawLog cabalPrizeDrawLog : cabalPrizeDrawLogList) {
            CabalPrizeDrawLogDTO cabalPrizeDrawLogDTO = new CabalPrizeDrawLogDTO();
            cabalPrizeDrawLogDTO.setCreateTime(DateApiUtil.format(cabalPrizeDrawLog.getCreateTime(), DateApiUtil.NORM_DATETIME_PATTERN));
            Integer rewardLevel = cabalPrizeDrawLog.getRewardLevel();
            String rewardLevelName = "";
            switch (rewardLevel) {
                case 0:
                    rewardLevelName = "特等奖";
                    break;
                case 1:
                    rewardLevelName = "一等奖";
                    break;
                case 2:
                    rewardLevelName = "二等奖";
                    break;
                case 3:
                    rewardLevelName = "三等奖";
                    break;
                case 4:
                    rewardLevelName = "四等奖";
                    break;
                case 5:
                    rewardLevelName = "幸运奖";
                    break;
                case 6:
                    rewardLevelName = "安慰奖";
                    break;
            }
            cabalPrizeDrawLogDTO.setRewardLevelName(rewardLevelName);
            cabalPrizeDrawLogDTO.setItemName(cabalPrizeDrawLog.getItemName());
            cabalPrizeDrawLogDTOList.add(cabalPrizeDrawLogDTO);
        }

        return cabalPrizeDrawLogDTOList;
    }

    @Override
    public List<PickUpItemDTO> selectPickUpItemList() {
        QueryWrapper<CabalPickUpItemConfig> queryWrapper = new QueryWrapper<CabalPickUpItemConfig>();
        DynamicDataSourceContextHolder.setContextKey(SystemConstants.DS_KEY_CABALMALL);
        List<CabalPickUpItemConfig> cabalPickUpItemConfigList = cabalPickUpItemConfigMapper.selectList(queryWrapper);
        DynamicDataSourceContextHolder.removeContextKey();

        List<PickUpItemDTO> pickUpItemDTOList = new ArrayList<>();
        if(CollectionUtils.isEmpty(cabalPickUpItemConfigList)) {
            return pickUpItemDTOList;
        }

        for(CabalPickUpItemConfig cabalPickUpItemConfig : cabalPickUpItemConfigList) {
            PickUpItemDTO pickUpItemDTO = new PickUpItemDTO();
            pickUpItemDTO.setItemId(cabalPickUpItemConfig.getItemId().toString());
            pickUpItemDTO.setItemOption(cabalPickUpItemConfig.getItemOption().toString());
            pickUpItemDTOList.add(pickUpItemDTO);
        }
        return pickUpItemDTOList;
    }


}

